<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 11/14/18
 * Time: 7:06 PM
 */

namespace caroltc\jenkinsapp\library;


class UserSession
{
    public $error = '';

    /**
     * 创建Session
     * @param $user_id
     * @param null
     * @return bool|array
     */
    public function createSession($user_id, $token = null)
    {
        try {
            if ($token === null) {
                $token = uniqid(md5($user_id) . ".");
            }
            $expire = time() + Facade::config('session_life', 86400);
            $session_data = [
                'user_id' => $user_id,
                'token' => $token,
                'expire' => $expire,
                'create_time' => date('Y-m-d H:i:s')
            ];
            $session_id = (new DbHandler())->createSession($session_data);
            if ($session_id) {
                return $session_data;
            }
            return false;
        } catch (\Exception $exception) {
            return false;
        }
    }

    /**
     * 通过token查找user
     * @param $token
     * @return bool|array
     */
    public function findUserByToken($token)
    {
        try {
            $DbHandler = new DbHandler();
            $session = $DbHandler->getSessionByToken($token);
            if (empty($session)) {
                throw new \Exception('session not exist');
            }
            if (intval($session['expire']) < time()) {
                throw new \Exception('session expire');
            }
            return $DbHandler->getUserByUserId($session['user_id']);
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

}